import axios from 'axios'
import store from '../store'

const utils = {
  /**
   * 比较两个数组是否相等
   * @param {*} arr1
   * @param {*} arr2
   * @returns
   */

  compareArray(arr1, arr2) {
    if (arr1.length !== arr2.length) return false
    arr1 = arr1.sort()
    arr2 = arr2.sort()
    let len = arr1.length
    for (let i = 0; i < len; i++) {
      if (arr1[i] !== arr2[i]) return false
    }
    return true
  },
  /**
   * 判断浏览器类型
   */
  browserType() {
    const userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
    const isOpera = userAgent.indexOf('Opera') > -1
    if (isOpera) {
      return 'Opera'
    }
    if (userAgent.indexOf('Firefox') > -1) {
      return 'Firefox'
    }
    if (userAgent.indexOf('Chrome') > -1) {
      return 'Chrome'
    }
    if (userAgent.indexOf('Safari') > -1) {
      return 'Safari'
    }
    if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
      return 'IE'
    }
  },

  /**
   * 是否有权限
   * @param {*} key
   * @returns
   */

  isAuth(key) {
    let list = key.split(',')
    let bool = true
    for (let i = 0; i < list.length; i++) {
      if (store.state.user.permList.indexOf(list[i]) === -1) {
        bool = false
        break
      }
    }
    return bool
  },
  /**
   * 清空登录信息
   */
  clearLoginInfo() {
    window.localStorage.removeItem('token')
    // 执行这个函数
    store.commit('resetStore')
  },

  /**
   * 获取前端字典
   * @param {类型} type
   * @returns
   */
  getDict(type) {
    if (type.indexOf('$') === 0) {
      let dict = store.state.common.dictListPrivate[type]
      if (typeof dict === 'object') {
        return dict || {}
      } else if (typeof dict === 'function') {
        return dict(utils.getDict)
      }
    }
  },

  /**
   * 发送浏览量
   * @param {*} name
   */
  sentRecord(name) {
    axios({
      url: axios.setUrl('abc'),
      method: 'post',
      data: axios.setData({
        closeTm: '',
        openPage: name,
        openTm: utils.formatDateTime(new Date()),
        operatorBrowser: utils.myBrowser()
      })
    }).then(({ data }) => {
      if (data && data.code === '0') {
        // 成功后执行的操作
      } else {
        // 失败
      }
    })
  },

  /**
   * 日期格式化 1999-01-01 12:34:56
   * @param {*} date
   */
  formatDateTime(date) {
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? '0' + m : m
    var d = date.getDate()
    d = d < 10 ? '0' + d : d
    var h = date.getHours()
    h = h < 10 ? '0' + h : h
    var minute = date.getMinutes()
    minute = minute < 10 ? '0' + minute : minute
    var second = date.getSeconds()
    second = second < 10 ? '0' + second : second
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
  }
}

export default utils
